import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Form, message, Row, Spin } from 'antd';
import { Ref, useEffect, useRef, useState } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { DelegateManageAPI } from '../common/type';
import {
  getFlowOrgTreeByOrgIDService,
  getUserDataList,
} from '@/services/BaseLayout';
import { commonDeptGetUser, getCompanyID, getDeptPosTreeIcon } from '@/utils';
import DeptPosLinkageUser from '@/components/DeptPosLinkageUser';

export const UpdateModal: React.FC<DelegateManageAPI.IUpdateModal> = ({
  onClose,
  visible,
}) => {
  /**
   * modal ref
   */
  const updateTreeRef: Ref<IOneModalRef> = useRef(null);

  /**
   * 表单 form
   */
  const [updateFrom] = Form.useForm();

  /**
   * 关闭弹窗
   */
  const onCloseModal = () => {
    if (updateTreeRef) {
      if (updateTreeRef.current) {
        if (updateTreeRef.current.onModalCancel) {
          updateTreeRef.current.onModalCancel();
        }
      }
    }
  };

  const {
    getFlowOrgTreeRun,
    getFlowOrgList,
    getFlowOrgTreeLoading,
  } = getFlowOrgTreeByOrgIDService();

  const {
    getUserRun,
    getUserLoading,
    getUserList,
    pramsObjInfo,
  } = getUserDataList((res: any) => {
    if (!(res && res?.msgFlag)) {
      message.error(res?.msg);
    }
  });

  useEffect(() => {
    let deptParams = {
      params: 0,
      flowType: 'null',
      orgID: getCompanyID(),
    };
    // getFlowOrgTreeRun(deptParams);
  }, []);

  /**
   * 处理树数据
   * @param data
   * @returns
   */
  const orgTreeData = (data: any[]): any[] => {
    return data?.map((item: any) => {
      return {
        ...item,
        title: (
          <div>
            {getDeptPosTreeIcon(String(item?.textType))}
            {item?.text}
          </div>
        ),
        searchtitle: item?.text,
        key: item?.id,
        value: item?.id,
        children:
          item?.children && item?.children?.length > 0
            ? orgTreeData(item?.children)
            : null,
        disabled: item?.textType == '2' ? false : true,
      };
    });
  };

  /**
   * 点击选中岗位
   * @param selectedKeys
   * @param selectedNodes
   */
  const onTreeSelect = (
    selectedKeys: any,
    selectedNodes: any,
    deptType: string,
  ) => {
    // checkForm?.setFieldsValue({ ownerID: null });
    if (deptType == 'entrust') {
      updateFrom?.setFieldsValue({ wtUser: undefined });
    }
    if (deptType == 'coverEntrust') {
      updateFrom?.setFieldsValue({ bwtUser: undefined });
    }
    let userListPayload = commonDeptGetUser([selectedNodes]);
    getUserRun({ ...userListPayload, deptType });
  };

  /**
   * 保存委托人 和被委托人数据
   */
  const [entrustUserList, setEntrustUserList] = useState<any>({
    entrustList: [],
    coverEntrustList: [],
  });

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={updateTreeRef}
        title={'添加委托'}
        width={document.body.clientWidth * 0.3}
        onCancel={onClose}
        bodyStyle={{
          padding: '5px 0px',
        }}
        centered
      >
        <Spin spinning={getFlowOrgTreeLoading || getUserLoading}>
          <div className={pageStyles['fromView-styles']}>
            <Form labelAlign="right" form={updateFrom}>
              <Row>
                {/* <Col span={24}>
                  <Form.Item
                    label={'委托部门'}
                    name="wtDept"
                    rules={[
                      {
                        required: true,
                        message: '请选择委托部门',
                      },
                    ]}
                  >
                    <TreeSelect
                      showSearch
                      treeNodeFilterProp={'searchtitle'}
                      placeholder="请选择委托部门"
                      treeData={orgTreeData(getFlowOrgList)}
                      loading={getFlowOrgTreeLoading}
                      onSelect={(selectedKeys: any, selectedNodes: any) => {
                        onTreeSelect(selectedKeys, selectedNodes, 'entrust');
                      }}
                    />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    label={'委托人'}
                    name="wtUser"
                    rules={[
                      {
                        required: true,
                        message: '请选择委托人',
                      },
                    ]}
                  >
                    <Select placeholder="请选择委托人" allowClear>
                      {entrustUserList?.entrustList?.map((item: any) => {
                        return (
                          <Select.Option
                            disabled={item?.id == getUserID() ? true : false}
                            value={item?.id}
                            key={item?.id}
                            searchtitle={item?.realName}
                          >
                            <MyIcon
                              style={{ marginRight: 5 }}
                              type="icon-lianxiren"
                            />
                            {item?.realName}
                          </Select.Option>
                        );
                      })}
                    </Select>
                  </Form.Item>
                </Col> */}

                <DeptPosLinkageUser
                  formRef={updateFrom}
                  colSpan={24}
                  isNO_label={true}
                  org_label={'被委托部门'}
                  user_label="被委托人"
                  orgamParams={{
                    params: 0,
                    // flowType: 0,
                    flowType: 'null',
                    orgID: getCompanyID(),
                    // orgID: getPosIDs(),
                    // orgID: getUserDepID()
                  }}
                  notUser={true}
                  isDeptRequired={true}
                  isUserRequired={false}
                  // isNo_showDepartment={true}
                  // isNO_showPosition={true}

                  isNo_selectCompany={false}
                  isNO_selectDepartment={false}
                  isNo_selectPosition={true}
                  // isNo_orgSelectChecks={false}
                  // isNo_userSelectChecks={false}

                  formCompanyID="bwtCompany"
                  formDepartmentID="bwtDept"
                  formPositionID="bwtPos"
                  formUserID="bwtUser"
                />
              </Row>
            </Form>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};
